var qbot_server_address = "ws://192.168.12.1:19002";
var qbot_client;
var qbot_charts;
var qbot_charts_option;
var qbot_speed = 0.0;
var qbot_timer;
var qbot_direction = 1;
var chart_cnt_data = [];
var qbot_runningTime = [];
var qbot_encoder_turns = [];
var qbot_motor2_turns = [];
var chart_len = 100;
var chart_cnt = chart_len;

var qbot_state = {}

function qbotChartsInit(){
    qbot_charts = echarts.init(document.getElementById('stauts-window'));

    // for (let i = 0; i < chart_len; i++)
    //     chart_cnt_data.push(i)

    qbot_charts_option = {
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: qbot_runningTime
        },
        yAxis: [
            {
                name: '编码器圈数',
                type: 'value'
            },
            {
                name: '电机圈数2',
                type: 'value'
            }
        ],
        legend: {
            data: ['编码器圈数', '电机圈数2']
        },
        series: [
            {
                name: '编码器圈数',
                type: 'line',
                smooth: true,
                symbol: 'none',
                data: qbot_encoder_turns,
                yAxisIndex: 0
            },
            {
                name: '电机圈数2',
                type: 'line',
                smooth: true,
                symbol: 'none',
                data: qbot_motor2_turns,
                yAxisIndex: 1
            }
        ]
    };

    qbot_charts.setOption(qbot_charts_option);
}

function autoYaxis() {
    qbot_charts_option.yAxis.min = Math.floor(Math.min.apply(null, qbot_encoder_turns)) - 5000;
    qbot_charts_option.yAxis.max = Math.floor(Math.max.apply(null, qbot_encoder_turns)) + 5000;
}

function addChartData() {
    qbot_encoder_turns.push(qbot_state.encoder.turns);
    qbot_motor2_turns.push(qbot_state.wheels[1].turns);
    qbot_runningTime.push(qbot_state.time);

    if (qbot_encoder_turns.length >= chart_len) {
        chart_cnt_data.shift();
        chart_cnt_data.push(chart_cnt);
        chart_cnt++;
        qbot_encoder_turns.shift();
        qbot_motor2_turns.shift();
        qbot_runningTime.shift();
    }

    //autoYaxis();
    qbot_charts.setOption(qbot_charts_option);
}

function display_state(id, onoff)
{
    if(onoff)
    {
        $("#"+id).attr("class", "fa fa-check")
        $("#"+id).attr("style", "font-size: 15px;color:green")
    }
    else{
        $("#"+id).attr("class", "fa fa-times")
        $("#"+id).attr("style", "font-size: 15px;color: #f1b60f")
    }
}

function ws_connect() {

    if (qbot_client != null && qbot_client.readyState == 1) {
        alert("already connected.")
        return
    }

    qbot_client = new WebSocket(qbot_server_address);

    qbot_client.onopen = () => {
        alert("websocket connected")
        $("#net-status").attr("class", "fa fa-check")
        $("#net-status").attr("style", "color:green")
        qbot_speed = 0.0
        qbot_timer = setInterval(
            () => {
                if (qbot_client.readyState == WebSocket.OPEN) {
                    qbot_client.send(JSON.stringify(
                        {
                            "clientId": "master",
                            "wsMsgType": "NOTIFICATION",
                            "modules": "robotState",
                            "data": {
                                "msgId": 11
                            }
                        }
                    ))
                }
            },
            500
        )
    }

    qbot_client.onmessage = (e) => {
        msg = JSON.parse(e.data)
        //console.log(msg)
        if (msg.data.msgId == 11) {
            qbot_state = msg.data.robotState;
            addChartData();
            $("#encoder-turns").text(qbot_state.encoder.turns.toFixed(1))
            $("#motor2-turns").text(qbot_state.wheels[1].turns.toFixed(1))
            $("#motor2-rpm").text(qbot_state.wheels[1].actualRpm.toFixed(1))
            display_state("encoder-status", qbot_state.encoder.ready)
            display_state("motor1-status", qbot_state.wheels[0].ready)
            display_state("motor2-status", qbot_state.wheels[1].ready)
            batteryPercent(qbot_state.BMS.RSOC.toFixed(0))
        }
    }

    qbot_client.onclose = () => {
        alert("连接已断开")
        $("#net-status").attr("class", "fa fa-times")
        $("#net-status").attr("style", "color: #f1b60f")
        clearInterval(qbot_timer);
    }

}

function speedUp() {
    if(qbot_speed<=1.5)qbot_speed += 0.1
    $("#qbot-speed").text(qbot_speed.toFixed(2))
    spin(qbot_direction)
}

function speedDown() {
    if(qbot_speed>=0.1)qbot_speed -= 0.1
    $("#qbot-speed").text(qbot_speed.toFixed(2))
    spin(qbot_direction)
}

function qbotSetPower(onoff) {
    let set_power = {
        "data": {
            "msgId": 9,
            "power": {
                "onoff": onoff
            }
        }
    }
    if(qbot_client == null)
    {
        return
    }
    if (qbot_client.readyState === WebSocket.OPEN) {
        console.log("power control")
        qbot_client.send(JSON.stringify(set_power))
    }
}

function spin(dire) {
    let vel = parseFloat($("#qbot-speed").text())
    qbot_direction = dire
    if(dire<0) vel = -vel
    if (Math.abs(vel) > 1.5) vel = 0.0
    let spin_set = {
        "clientId": "master",
        "wsMsgType": "NOTIFICATION",
        "modules": "adminControl",
        "data": {
            "msgId": 4,
            "move": {
                "linear": {
                    "x": vel
                }
            }
        }
    }
    if(qbot_client == null)
    {
        return
    }
    if (qbot_client.readyState === WebSocket.OPEN) {
        console.log("spin")
        qbot_client.send(JSON.stringify(spin_set))
    }
}

function clearOdom() {
    let clear = {
        "clientId": "master",
        "wsMsgType": "NOTIFICATION",
        "modules": "adminControl",
        "data": {
            "msgId": 3
        }
    }
    if (qbot_client.readyState === WebSocket.OPEN) {
        console.log("clear odom")
        qbot_client.send(JSON.stringify(clear))
    }
}

function spinStop() {
    let spin_set = {
        "clientId": "master",
        "wsMsgType": "NOTIFICATION",
        "modules": "adminControl",
        "data": {
            "msgId": 4,
            "move": {
                "linear": {
                    "x": 0.0
                }
            }
        }
    }
    if (qbot_client.readyState === WebSocket.OPEN) {
        console.log("spin")
        qbot_client.send(JSON.stringify(spin_set))
    }
}